//
//  YZDBManager.m
//  CocoaAsyncSocketClient
//
//  Created by lixiaoyi on 2018/7/4.
//  Copyright © 2018年 lixiaoyi. All rights reserved.
//

#import "YZDBManager.h"
#import "FMDB.h"
#import "ImMessage.pbobjc.h"
#import "YZMessageModel.h"
#import "YZMessageFrame.h"
#import "YZMessageHelper.h"
#import "YZMessageConst.h"
#import "varint.h"
#import "YZChatUtils.h"
#import "YZChatPeer.h"
#import "YZMessageListModel.h"
#import "YZFriendModel.h"
#import "YZUser.h"

#define   kCachePath   [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
#define   kDBPath         [NSString stringWithFormat:@"%@/YZChatDB.sqlite",kCachePath]

/* ChatRecordTable */
// 发送者
#define kSender             @"sender"

// 发送时间
#define kSendTime           @"sendTime"

// 接收者
#define kReceiver           @"receiver"

// 附件路径：（图片，语音，视频等）
#define kFilePath           @"filePath"

// 缩略图路径：（比如视频的缩略图）
#define kFileKey            @"fileKey"

// 发送的内容：NSData
#define kSendContent        @"content"

// 是否发送者 0:false 1:true
#define kisSender           @"isSender"

// 发送状态 0:false 1:true
#define kSendStatus         @"sendStatus"

// 消息类型
#define kMediaType          @"mediaType"

// 发送者头像
#define kSenderAvatar       @"senderAvatar"

// 接收者头像
#define kReceiverAvatar     @"receiverAvatar"

#define kAvatar             @"avatar"


/* ChatMessageListTable */
#define kShowUserId         @"showUserid"

#define KLastContent        @"lastContent"
// 小红点的数量
#define kRedHotNum          @"redHotNum"
// 发送者昵称
#define kNickName         @"nickName"


/* NewFriendTable */
// 新朋友的uid
#define kTargetId           @"targetId"
// 新朋友的名字
#define kFriendName         @"name"
// 新朋友头像的url
#define kIconUrl            @"iconUrl"
// 新朋友的申请审核信息
#define kInfo               @"info"
// 新朋友的审核状态（已同意，已拒绝等）
#define kAuditStatus             @"auditStatus"

@implementation YZDBManager

static YZDBManager *manager = nil;
+ (instancetype)sharedManage{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [YZDBManager new];
    });
    
    return manager;
}

- (BOOL)createTableName:(NSString *)tableName {
    BOOL ret = NO;
    NSString *sqlStr = @"";
    
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    NSLog(@"DBPath------>%@",kDBPath);
    if ([db open]) {
        if ([tableName isEqualToString:kChatRecordTable]) {
            sqlStr = [NSString stringWithFormat:
                      @"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT, %@ TEXT, %@ INTEGER, %@ TEXT, %@ TEXT, %@ TEXT, %@ BLOB, %@ INTEGER, %@ INTEGER, %@ TEXT, %@ TEXT, %@ TEXT)",tableName, kSender, kSendTime,kReceiver, kFilePath,kFileKey, kSendContent, kisSender, kSendStatus, kMediaType, kSenderAvatar,kReceiverAvatar];
        } else if ([tableName isEqualToString:kChatMessageListTable]) {
            sqlStr = [NSString stringWithFormat:
                      @"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT, %@ TEXT, %@ INTEGER, %@ TEXT, %@ TEXT, %@ TEXT, %@ INTEGER, %@ TEXT, %@ TEXT)",tableName, kShowUserId,kSendTime,KLastContent,kSender, kReceiver,kRedHotNum, kAvatar,kNickName];
        } else if ([tableName isEqualToString:kNewFriendTable]) {
            sqlStr = [NSString stringWithFormat:
                      @"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT, %@ TEXT, %@ TEXT, %@ TEXT, %@ TEXT, %@ INTEGER)",tableName,kTargetId, kFriendName,kIconUrl,kInfo,kAuditStatus];
        }
        
        
        ret = [db executeUpdate:sqlStr];
        [db close];
    }
    return ret;
}


- (BOOL)insertData:(NSData *)data
         mediaType:(NSString *)mediaType
          sendTime:(NSUInteger)sendTime
          filePath:(NSString *)filePath
           fileKey:(NSString *)fileKey
          isSender:(NSInteger)isSender
            status:(NSInteger)sendStatus
             table:(NSString *)tableName
        senderAvatar:(NSString *)senderAvatar
    receiverAvatar:(NSString *)receiverAvatar{
    BOOL ret = NO;
    NSString *sqlStr = @"";
    
    ImMessage *message = [self createMessage:@"YZIMP"
                                     version: @"1.0"
                                      userId:[YZChatPeer shared].sender
                                   userToken:[YZUser sharedInstance].token
                                   messageId:1
                                 messageType:@"data"
                                 messageTime:sendTime
                                    termType:@"iOS"
                                    receiver:[YZChatPeer shared].receiver
                                      sender:[YZChatPeer shared].sender
                               ctrlMessageId:0
                                   mediaType:mediaType
                                    playload:data
                                    sendTime:sendTime];
    
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        if ([tableName isEqualToString:kChatRecordTable]) {
            // 插入NSData类型
            sqlStr = @"INSERT INTO ChatRecordTable(id,sender,sendTime,receiver,filePath,fileKey,content,isSender,sendStatus,mediaType,senderAvatar,receiverAvatar) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
            ret = [db executeUpdate:sqlStr,NULL,message.sender,@(message.messageTime),message.receiver,filePath,fileKey,data,@(isSender),@(sendStatus),message.mediaType,senderAvatar,receiverAvatar];
        }
        
        [db close];
    }
    
    return ret;
}

/**
 插入ChatMessageListTable数据
 
 @param data data
 @param tableName ChatMessageListTable
 @return 插入结果
 */
- (BOOL)insertMessageListData:(id)data
                    tableName:(NSString *)tableName {
    BOOL ret = NO;
    NSString *sqlStr = @"";
    
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
         if ([tableName isEqualToString:kChatMessageListTable]) {
            YZMessageListModel *model = (YZMessageListModel*)data;
            sqlStr = @"INSERT INTO ChatMessageListTable(id,showUserid,sendTime,lastContent,sender,receiver,redHotNum,avatar,nickName) VALUES(?,?,?,?,?,?,?,?,?)";
            
            ret = [db executeUpdate:sqlStr,NULL,model.showUserId,@(model.time),model.message,model.showUserId,model.receiver,model.redHotNumber,model.imageName,model.name];
        }
        
        [db close];
    }
    
    return ret;
}

/**
 插入新朋友表数据
 
 @param data 数据
 @param tableName NewFriendTable
 @return 插入结果
 */
- (BOOL)insertNewFriendData:(id)data
                  tableName:(NSString *)tableName {
    BOOL ret = NO;
    NSString *sqlStr = @"";
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    
    if ([db open]) {
        if ([tableName isEqualToString:kNewFriendTable]) {
            YZFriendModel *model = (YZFriendModel*)data;
            sqlStr = @"INSERT INTO NewFriendTable(id,targetId,name,iconUrl,info,auditStatus) VALUES(?,?,?,?,?,?)";
            
            ret = [db executeUpdate:sqlStr,NULL,model.targetId,model.name,model.iconName,model.info,@(model.friendState)];
        }
        
        [db close];
    }
    
    return ret;
    
}

- (BOOL)deleteDataFromTable:(NSString *)tableName withCondition:(NSString *)conditionStr{
    BOOL ret = NO;
    NSString *sqlStr = @"";
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        if (!conditionStr || [conditionStr isEqualToString:@""]) {
            sqlStr = [NSString stringWithFormat:@"DELETE FROM %@",tableName];
        } else {
            sqlStr = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@",tableName,conditionStr];
        }
        ret = [db executeUpdate:sqlStr];
        [db close];
    }
    
    return ret;
}

- (BOOL)updateData:(id)data table:(NSString *)table andCondition:(NSString *)conditionStr{
    BOOL ret = NO;
    NSString *sqlStr = @"";
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        sqlStr = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@",table,data,conditionStr];
        ret = [db executeUpdate:sqlStr];
        [db close];
    }
    
    return ret;
}

- (id)queryDataFromTable:(NSString *)tableName andCondition:(NSString *)conditionStr{
    NSString *sqlStr = @"";
    NSMutableArray *dataArray = [NSMutableArray array];
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    YZMessageFrame *tempMessageF = nil;
    if ([db open]) {
        FMResultSet *result = nil;
       
        if (!conditionStr || [conditionStr isEqualToString:@""]) {
            sqlStr = [NSString stringWithFormat:@"SELECT * FROM %@",tableName];
        } else {
            sqlStr = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@",tableName,conditionStr];
        }
        
        result = [db executeQuery:sqlStr];
        
        while ([result next]) {
            
            if ([tableName isEqualToString:kChatRecordTable]) {
                // 发送内容
                ImMessage *message = [[ImMessage alloc] init];
                NSData *content = [result dataForColumn:kSendContent];
                
                // 发送时间
                NSUInteger time = [result longLongIntForColumn:kSendTime];
                
                // 消息类型
                NSString *mediaType = [result stringForColumn:kMediaType];
                
                message = [self createMessage:@"YZIMP"
                                      version: @"1.0"
                                       userId:[YZChatPeer shared].sender
                                    userToken:[YZUser sharedInstance].token
                                    messageId:1
                                  messageType:@"data"
                                  messageTime:time
                                     termType:@"iOS"
                                     receiver:[YZChatPeer shared].receiver
                                       sender:[YZChatPeer shared].sender
                                ctrlMessageId:0
                                    mediaType:mediaType
                                     playload:content
                                     sendTime:time];
                
                // 附件
                NSString *filePath = [result stringForColumn:kFilePath];
                
                // 缩略图
                NSString *fileKey = [result stringForColumn:kFileKey];
                
                // 消息类型
                NSString *messageType = [result stringForColumn:kMediaType];
                if ([message.mediaType isEqualToString:@"text/plain"]) {
                    messageType = TypeText;
                } else if ([message.mediaType isEqualToString:@"image/*"]) {
                    messageType = TypePic;
                } else if ([message.mediaType isEqualToString:@"audio/aac"]) {
                    messageType = TypeVoice;
                } else if ([message.mediaType isEqualToString:@"video/mp4"]) {
                    messageType = TypeVideo;
                }
                
                // 是否发送者
                int iSender = [result intForColumn:kisSender];
                BOOL bSender = NO;
                if (1 == iSender) {
                    bSender = YES;
                }
                
                // 发送者头像
                NSString *senderAvatar = [result stringForColumn:@"senderAvatar"];
                
                // 接收者头像
                NSString *receiverAvatar = [result stringForColumn:@"receiverAvatar"];
                
                YZMessageFrame *messageF = [YZMessageHelper createMessageFrame:messageType imMessage:message path:filePath fileKey:fileKey isSender:bSender rececivedSenderbySelf:NO senderAvatar:senderAvatar receiverAvatar:receiverAvatar];
                
                // 是否发送成功
                int sendStauts = [result intForColumn:kSendStatus];
                if (0 == sendStauts) {
                    messageF.model.message.deliveryState = ICMessageDeliveryState_Failure;
                } else if (1 == sendStauts) {
                    messageF.model.message.deliveryState = ICMessageDeliveryState_Delivered;
                }
                
                int64_t minSecond = messageF.model.message.messageTime - tempMessageF.model.message.messageTime;
                
                // 第一条记录或者消息时间间隔大于1分钟
                if ([dataArray count] == 0 || minSecond > 60 * 3 * 1000) {
                    // 添加一条时间消息
                    ImMessage *im = [[ImMessage alloc] init];
                    im.messageTime = messageF.model.message.messageTime ;
                    YZMessageFrame *msgF = [YZMessageHelper createMessageFrame:TypeSystem imMessage:im path:nil fileKey:fileKey isSender:YES rececivedSenderbySelf:NO  senderAvatar:@"" receiverAvatar:@""];
                    [dataArray addObject:msgF];
                    
                    self.lastVisibleTime = messageF.model.message.messageTime;
                    tempMessageF = messageF;
                }
                [dataArray addObject:messageF];
            }
            else if ([tableName isEqualToString:kChatMessageListTable]) {
                // showUserId
                NSString *name = [result stringForColumn:kNickName];
                
                // sendtime
//                NSUInteger time = [result intForColumn:kSendTime];
                int64_t time = [result longLongIntForColumn:kSendTime];
                
                
                // lastContent
                NSData *content = [result dataForColumn:KLastContent];
                
                // sender
                NSString *sender = [result stringForColumn:kSender];
                
                // receiver
                NSString *receiver = [result stringForColumn:kReceiver];
                
                // redhotnum
                NSNumber *redHotDotNum = @([result intForColumn:kRedHotNum]);
                
                // 头像
                NSString *avatar = [result stringForColumn:kAvatar];
                
                YZMessageListModel *model = [YZMessageListModel new];
                model.name = name;
                model.imageName = avatar;
                model.time = time;
                model.message = [[NSString alloc] initWithData:content encoding:NSUTF8StringEncoding];
                model.receiver = receiver;
                model.showUserId = sender;
                model.redHotNumber = redHotDotNum;
                
                [dataArray addObject:model];
            } else if ([tableName isEqualToString:kNewFriendTable]) {
                // targetId
                NSString *targetId = [result stringForColumn:kTargetId];
                
                // name
                NSString *name = [result stringForColumn:kFriendName];
                
                // iconUrl
                NSString *iconUrl = [result stringForColumn:kIconUrl];
                
                // info
                NSString *info = [result stringForColumn:kInfo];
                
                // auditStatus
                int auditStatus = [result intForColumn:kAuditStatus];
                
                YZFriendModel *friendModel = [YZFriendModel new];
                friendModel.targetId = targetId;
                friendModel.name = name;
                friendModel.iconName = iconUrl;
                friendModel.info = info;
                friendModel.friendState = auditStatus;
                [dataArray addObject:friendModel];
            }
        }
        
        [db close];
    }
    return dataArray;
}

- (void)sendMessageTime:(YZMessageFrame *)messageF {
    // 发送时间
    ImMessage *im = [[ImMessage alloc] init];
    im.messageTime = messageF.model.message.messageTime ;
    YZMessageFrame *msgF = [YZMessageHelper createMessageFrame:TypeSystem imMessage:im path:nil fileKey:nil isSender:YES rececivedSenderbySelf:NO senderAvatar:@"" receiverAvatar:@""];
}

- (ImMessage *)createMessage:(NSString *)protocol
                     version:(NSString *)version
                      userId:(NSString *)userId
                   userToken:(NSString *)userToken
                   messageId:(UInt32)messageId
                 messageType:(NSString *)messageType
                 messageTime:(UInt64)messageTime
                    termType:(NSString *)termType
                    receiver:(NSString *)receiver
                      sender:(NSString *)sender
               ctrlMessageId:(UInt32)ctrlMessageId
                   mediaType:(NSString *)mediaType
                    playload:(NSData *)playload
                    sendTime:(UInt64)sendTime{
    
    
    ImMessage *_mess = [ImMessage new];
    _mess.protocol = protocol;
    _mess.version = version;
    _mess.userId = userId;
    _mess.userToken = userToken;
    _mess.messageId = messageId;
    _mess.messageType = messageType;
    _mess.messageTime = sendTime;
    _mess.termType = termType;
    _mess.receiver = receiver;
    _mess.sender = sender;
    _mess.ctrlMessageId = ctrlMessageId;
    _mess.mediaType = mediaType;
    _mess.payload = playload;
    
    return _mess;
}

/**
 获取记录条数
 
 @param tableName 表名
 @return 记录条数
 */
- (NSUInteger)getDataCountFromTable:(NSString *)tableName {
    NSString *queryStr = [NSString stringWithFormat:@"select count(*) from %@",tableName];
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    NSUInteger rowCount = 0;
    if ([db open]) {
        rowCount = [db intForQuery:queryStr];
        [db close];
    }
    
    return rowCount;
}

@end
